package com.smartcampusbackend.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.smartcampusbackend.model.SystemLog;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
import java.util.Map;

@Mapper
public interface SystemLogMapper extends BaseMapper<SystemLog> {
    
    /**
     * 获取日志统计信息
     */
    @Select("SELECT " +
            "COUNT(*) as total, " +
            "COUNT(CASE WHEN log_type = 'LOGIN' THEN 1 END) as loginCount, " +
            "COUNT(CASE WHEN log_type = 'OPERATION' THEN 1 END) as operationCount, " +
            "COUNT(CASE WHEN log_type = 'DATA' THEN 1 END) as dataCount, " +
            "COUNT(CASE WHEN log_type = 'ERROR' THEN 1 END) as errorCount, " +
            "COUNT(CASE WHEN status = 'FAILED' THEN 1 END) as failedCount " +
            "FROM system_log " +
            "WHERE DATE(create_time) = CURDATE()")
    Map<String, Object> getTodayStats();
    
    /**
     * 获取用户最近的日志
     */
    @Select("SELECT * FROM system_log WHERE username = #{username} ORDER BY create_time DESC LIMIT #{limit}")
    List<SystemLog> getRecentLogsByUsername(@Param("username") String username, @Param("limit") int limit);
    
    /**
     * 获取指定时间范围的日志统计
     */
    @Select("SELECT " +
            "DATE(create_time) as date, " +
            "COUNT(*) as total, " +
            "COUNT(CASE WHEN log_type = 'LOGIN' THEN 1 END) as loginCount, " +
            "COUNT(CASE WHEN status = 'FAILED' THEN 1 END) as failedCount " +
            "FROM system_log " +
            "WHERE create_time BETWEEN #{startDate} AND #{endDate} " +
            "GROUP BY DATE(create_time) " +
            "ORDER BY date")
    List<Map<String, Object>> getLogStatsByDateRange(@Param("startDate") String startDate, @Param("endDate") String endDate);

    /**
     * 统计近10分钟有登录日志的不同用户数
     */
    @Select("SELECT COUNT(DISTINCT username) FROM system_log WHERE log_type = 'LOGIN' AND create_time >= #{since}")
    long countRecentLoginUsers(@Param("since") String since);
} 